class StoreController < ApplicationController
  before_filter :find_cart, :except => :empty_cart
  protect_from_forgery :except => [:add_province,:add_city,:add_region]
  def index

  end

  def add_to_cart
    begin
      Product.find(params[:id])
    rescue ActiveRecord::RecordNotFound
      logger.error("Attempt to access invalid product #{params[:id]}")
      redirect_to_index("Invalid product")
    else
      quantity = params[:quantity] ? (params[:quantity].to_i):1
      @current_item = @cart.add_product(params[:id],quantity)
      if request.xhr?
        render :template=>'/store/_cart',:layout=>false
      else
        redirect_to_index
      end
    end
  end

  def remove_from_cart
    @cart.items.each do |i|
      @cart.items.delete(i)   if i.product_id == params[:id]
    end
    if request.xhr?
      render :template=>'/store/_cart',:layout=>false
    else
      redirect_to_index
    end
  end

  def empty_cart
    session[:cart] = nil
    render :text=>'ok'
  end

  def migrate
    #    categories = Category.find(:all,:conditions=>"description is not null and description <> ''")
    #    categories.each do |c|
    #      aproduct = AbstractProduct.create(:description=>c.description,:image_url=>File.basename(c.image_path))
    #      aproduct.products = c.products
    #      if aproduct.save
    #        app_root = File.expand_path(RAILS_ROOT)
    #        Dir.mkdir(app_root >> "/public/abstract_product/image_url/#{aproduct.id}",0775)
    #      end
    #    end
    render :text=>AbstractProduct.cp_from_cate
  end

  def update_category_product_size
    count = 0
    Category.find(:all).each do |c|
      c.products_count = c.products.length
      if c.save!
        count +=1
      end
    end
    render :text=>count
  end

  #  def add_province
  #    data = JSON.parse(params[:data])
  #    count = 0
  #    data["province"].each do |p|
  #      count +=1
  #      province = Province.create(:name=>p["name"])
  #      p["city"].sort!{|a,b|a["post_code"]<=>b["post_code"]}
  #      p["city"].each do |c|
  #        city = province.cities.create(:name=>c["name"],:post_code=>c["post_code"],:long_distance_code=>c["long_distance_code"])
  #        c["region"].sort!{|a,b|a["post_code"]<=>b["post_code"]}
  #        c["region"].each do |r|
  #          city.regions.create(:name=>r["name"],:post_code=>r["post_code"])
  #        end
  #      end
  #    end
  #    render :text=>count.to_s
  #  end

  #  def get_province
  #    json_data =  Province.find(:all,:include=>:cities).map{|p|
  #      {"id"=>p.id,"name"=>p.name,
  #        "cities"=>p.cities.map{|c|{"id"=>c.id,"name"=>c.name,
  #            "post_code"=>c.post_code,
  #            "long_distance_code"=>c.long_distance_code,
  #            "region"=>c.regions.map{|r|{"id"=>r.id,"name"=>r.name,"post_code"=>r.post_code}}
  #          }
  #        }
  #
  #      }
  #    }
  #    render :text=>json_data.to_json
  #  end
  
end
